package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备上报数据管理Service业务层处理
 * 
 * @author ych
 * @date 2025-10-19
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IotClientConfig iotClientConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询设备上报数据管理
     * 
     * @param id 设备上报数据管理主键
     * @return 设备上报数据管理
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备上报数据管理列表
     * 
     * @param deviceData 设备上报数据管理
     * @return 设备上报数据管理
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备上报数据管理
     * 
     * @param deviceData 设备上报数据管理
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData)?1:0;
    }

    /**
     * 修改设备上报数据管理
     * 
     * @param deviceData 设备上报数据管理
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData)?1:0;
    }

    /**
     * 批量删除设备上报数据管理
     * 
     * @param ids 需要删除的设备上报数据管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备上报数据管理信息
     * 
     * @param id 设备上报数据管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id)?1:0;
    }


    /**
     * 批量保存数据
     *
     * @param contentStr
     *
     */
    @Override
    public void batchInsertByContentStr(String contentStr) {
        if (contentStr == null) {
            return;
        }
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        //查询设备id
        String deviceId = jsonObject.getByPath("notify_data.header.device_id", String.class);
        //通过id获取设备
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, deviceId);
        Device device = deviceMapper.selectOne(queryWrapper);
        if (device == null) {
            return;
        }

        //保存数据
        JSONObject properties = (JSONObject)jsonObject.getByPath("notify_data.body.services[0].properties");
        Set<String> keys = properties.keySet();
        String timeStr = jsonObject.get("event_time", String.class);
        LocalDateTime parse = LocalDateTimeUtil.parse(timeStr,"yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime localDateTime = DateTimeZoneConverter.utcToShanghai(parse);
        List<DeviceData> list = new ArrayList<>();
        for (String key : keys) {
            Object value = properties.get(key);

            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
            deviceData.setId(null);
            deviceData.setAccessLocation(device.getBindingLocation());
            deviceData.setFunctionId(key);
            deviceData.setDataValue(value + "");
            deviceData.setAlarmTime(localDateTime);

            list.add(deviceData);
        }
        //批量保存
        try {
            saveBatch(list);
            //向Redis中放数据
            redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).put(deviceId,JSONUtil.toJsonStr(list));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
@Transactional
    @Override
    public void cleandOldData(Integer minute) {
        //查询10分钟前最后一个id值
       Long id =  deviceMapper.getLastId(minute);
       //把小于等于这个id值的全部数据移到历史表中
        deviceMapper.insertIntoHistory(id);
        //删除小于等于这个id数据
        deviceMapper.deleteOldLeId(id);
    }
}
